$(function(){
	$("#functionNav").attr("href",navAddr);
	String.prototype.trim=function(){
	   return this.replace(/(^\s*)|(\s*$)/g, "");
	}
	
	Array.prototype.remove=function(dx) 
	{ 
	  if(isNaN(dx)||dx>this.length){return false;} 
	  for(var i=0,n=0;i<this.length;i++){ 
	    if(this[i]!=this[dx]){ 
	      this[n++]=this[i] 
	    } 
	  } 
	  this.length-=1 
	};
	
	var year;
	//表格表头列
	var djlbCols;
	//所有申请人列表
	var sqrList;
	//每个org下的申请人列表
	var sqrGroups = {};
	
	var sqbmMap = {};
	var sqrMap = {};
	
	var rootOrgId;
	
	var searchParams = $("#stat-form").serializeObject();
	var tableColumn = createColumn(searchParams);
	
	//初始化下拉列表
	initSelect(searchParams.sqbmid);
	
	//必须在initSelect()之后调用
	initTableHead();
	
	initTableFoot();
	
	createTableWithOutPage('#stat-show', ProjectName+'/colstat.getBusinessTotal.do', "month", tableColumn, searchParams);
	
	//统计按钮
	$('#stat-yw-query').click(function(){
		searchParams = $("#stat-form").serializeObject();
		tableColumn = createColumn(searchParams);
		if(!isValidStr(searchParams.year)){
			alertFunc("统计年度不能为空！");
			return;
		}
		initTableHead();
		initTableFoot();
		//销毁重绘
		$('#stat-show').bootstrapTable('destroy');
		createTableWithOutPage('#stat-show', ProjectName+'/colstat.getBusinessTotal.do', "month", tableColumn, searchParams);
	});
	
	//选择具体部门时，刷新申请人列表
	$('#sqbm').click(function(){
		var orgId = $(this).val();
		if(isValidStr(orgId)){
			//每次请求数据库
//			var sqrJson = ajaxResult("get", false, ProjectName+"/root.getUsersByOrg.do", {'orgId':orgId});
//			loadSelect("#sqr", sqrJson.rows, 'userid', 'username');
			//缓存申请人列表
			if(!sqrGroups[orgId]){
				var list = [];
				$.each(sqrList, function(i, item){
					if(item.orgid==orgId){
						 var map = {};
						 map['userid'] = item.userid;
						 map['username'] = item.username;
						 list.push(map);
					}
				});
				sqrGroups[orgId] = list;
			}
		}else{
			orgId = rootOrgId;
			var list = [];
			$.each(sqrList, function(i, item){
				 var map = {};
				 map['userid'] = item.userid;
				 map['username'] = item.username;
				 list.push(map);
			});
			sqrGroups[orgId] = list;
		}
		loadSelect("#sqr", sqrGroups[orgId], 'userid', 'username'); 
	});
	
	$('#stat-yw-export').click(function(){
		//不加这一句，意在只对上一次统计操作进行导出。否则，导出就变成'统计+导出'
//		searchParams = $("#stat-form").serializeObject();
		searchParams.title = $('#table-head').html();
		searchParams.author = userInfo.username;
		searchParams.type = 'ywzltj';
		
//		ajaxResult("get", false, ProjectName+'/colstat.export.do', searchParams);
		$.fileDownload(ProjectName+'/colstat.export.do', {
			data: $.param(searchParams),
			httpMethod: "post",
			successCallback: function (url) {
				console.log('文件下载成功！')
			},
			failCallback: function (responseHtml, url, error) { 
				console.log('文件下载失败！')
			}
		});
	});
	
	function createTable(){
		//导出按钮设为不可用
		$('#stat-yw-export').attr('disabled', true);
		
		$('#stat-show').bootstrapTable('destroy');		
		$('#stat-show').bootstrapTable({
			url: ProjectName+'/colstat.getBusinessTotal.do',
			method: 'get',
			sidePagination: "server",
			queryParams: searchParams,
			columns: tableColumn,
			onLoadSuccess: function(d){  //加载成功时执行  
	             data=d;
	             //导出按钮可用
	             $('#stat-yw-export').attr('disabled', false);
	        }
		});
	};
	
	function isValidStr(str){
		if(str && str.trim().length>0)
			return true;
		return false;
	}
	
	function initSelect(orgId){
		//统计年度下拉列表初始化
		year = new Date().getFullYear();
		var arr = [];
		for(var i=2016; i<=year; i++){
			var map = {};
			map['key'] = i;
			map['value'] = i;
			arr.push(map);
		}
		loadSelect("#tjnd", arr, 'value', 'key');
		//设置当年的option为选中状态
		$("#tjnd option[value="+year+"]").attr("selected", true);
		
		var sqbmJson = ajaxResult("get", false, ProjectName+"/root.getOrganization.do");
		sqbmJson = sqbmJson.rows;
		var isOrgidEmpty = !isValidStr(rootOrgId);
		//orgId = 'shandongbowuguan';是馆内所有申请人
		//去掉'山东博物馆'这条记录
		//找到pid为0的orgid
		$.each(sqbmJson, function(index, item){
			if(item.pId=='0'){
				if(isOrgidEmpty) 
					rootOrgId = item.orgid;
				sqbmJson.remove(index);
				//跳出数组遍历
				return false;
			}
		});
		$.each(sqbmJson, function(index, item){
			sqbmMap[item.orgid] = item.name;
		});
		loadSelect("#sqbm", sqbmJson, 'orgid', 'name');
		var sqrJson = ajaxResult("get", false, ProjectName+"/root.getUsersByOrg.do", {'orgId':rootOrgId});
		loadSelect("#sqr", sqrJson.rows, 'userid', 'username');
		sqrList = sqrJson.rows;
		$.each(sqrList, function(i, item){
			 sqrMap[item.userid] = item.username;
		});
	}
	
	function initTableHead(){
		var html = '业务总量统计';
		var con = '';
		var djlbJson = {'rz':'征集', 'ctk':'出退库', 'yk':'移库', 'xgbm':'编目修改', 'zx':'注销'};
		//初始加载时，没有选项。
		var noSelected = true;
		for(var key in searchParams){
			var value = searchParams[key];
			
			if(!isValidStr(value+""))
				continue;
			
			if(key == 'djlb')
				con += '单据类别：'+djlbJson[value]+'；'
			if(key == 'year')
				con += '统计年度：'+value+'；'
			if(key == 'sqbmid')
				con += '单据部门：'+sqbmMap[value]+'；'
			if(key == 'sqrid')
				con += '申请人：'+sqrMap[value]+'；'
				
			noSelected = false;
		}
		//初始设为当前年份，但无法捕捉参数，人为加上该过滤选项
		if(noSelected)
			con += '统计年度：'+year+''
		if(con)
			html += ' ( ' + con + ' )';
		$('#table-head').html(html);
	}
	
	function initTableFoot(){
		if(!userInfo)
			getUserRight();
		
		var content = "";
		content += '制表人：'+userInfo.username+'<br>';
		content += '统计时间：'+nowDate();
		
		$('#table-foot').html(content);
	}

	function createColumn(paras){
		var cols, tableName;
		var conditionOnX = isValidStr(paras.djlb);
		var conditionX = paras.djlb;
		
		if(!djlbCols){
			var tColumn = [];
			var firstCol = {};
			firstCol['field'] = 'month';
			firstCol['align'] = 'center';
			firstCol['title'] = '月份';
			tColumn.push(firstCol);
			
			var colNames = ['征集单','征集藏品','出退库申请单','出退库藏品','移库单','移库藏品','编目修改单','注销单'];
			for(var i=1; i<=colNames.length; i++){
				map = {}
				map['field'] = i;
				map['title'] = colNames[i-1];
				map['align'] = 'center';
				tColumn.push(map);
			}
			djlbCols = tColumn;
		}

		if(conditionOnX)
			return filterColumn(conditionX, djlbCols);
		
		return djlbCols;
	}
	
	function filterColumn(conditionX, cols){
		var newCols = [];
		newCols.push(cols[0]);
		if(conditionX=='rz'){
			newCols.push(cols[1]);
			newCols.push(cols[2]);
		}else if(conditionX=='ctk'){
			newCols.push(cols[3]);
			newCols.push(cols[4]);
		}else if(conditionX=='yk'){
			newCols.push(cols[5]);
			newCols.push(cols[6]);
		}else if(conditionX=='xgbm'){
			newCols.push(cols[7]);
		}else
			newCols.push(cols[8]);
		
		return newCols;
	}
	
});